package com.itqf.dao.impl;

import com.itqf.dao.GoodsDao;
import com.itqf.pojo.Goods;
import com.itqf.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * projectName: gpshop
 *
 * @author: 赵伟风
 * time: 2021/7/22 17:09
 * description:
 */
public class GoodsDaoImpl implements GoodsDao {
    /**
     * 数据库的分页查询语句!
     *
     * @param sql      动态sql语句!
     * @param index    占位符的值
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public List<Goods> queryByPage(String sql, String index, int page, int pageSize) throws SQLException {

        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        List<Goods> goodsList = queryRunner.query(sql, new BeanListHandler<>(Goods.class), index, (page - 1) * pageSize, pageSize);

        return goodsList;
    }

    /**
     * 查询总条数
     *
     * @param sql   动态sql语句
     * @param index 占位符值
     * @return
     */
    @Override
    public Long queryTotal(String sql, String index) throws SQLException {


        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        Long count = (Long) queryRunner.query(sql, new ScalarHandler(), index);

        return count;
    }

    /**
     * 查询商单条品
     *
     * @param gId
     * @return
     */
    @Override
    public Goods queryGoods(String gId) throws SQLException {

        String sql = "select g_id gId,g_name gName,g_price gPrice,g_img gImg,g_rank gRank,g_date gDate,g_detail gDetail " +
        "from goods where g_id = ? ;";

        QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

        Goods goods = queryRunner.query(sql, new BeanHandler<>(Goods.class), gId);

        return goods;
    }
}
